﻿using System;
using System.Configuration;
using System.Web;
using System.Collections.Generic;

namespace Shuba.Web.bulk_upload
{
    public partial class alternate_um_add : basePage
    {
        string msg = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Form.DefaultFocus = txtBranchCode.ClientID;
            this.Form.DefaultButton = btnSubmit.UniqueID;

            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("ALTERNATE_UM");

                if (!IsUserAdd(acl) && !IsUserEdit(acl))
                {
                    msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                txtStartDate.Text = ProcessingDate().ToString("dd MMMM yyyy");
                txtToDate.Text = ProcessingDate().ToString("dd MMMM yyyy");

                LabelTitle.Text = GetPageTitle("ALTERNATE_UM");
                                
                if (Request.QueryString["a"] == "ed")
                {
                    BindData();
                    txtNIP.Enabled = false;
                    txtBranchCode.Enabled = false;
                }
            }
        }

        private void BindData()
        {
            hidOldNIP.Value = Request.QueryString["id"];
            hidOldUnitCode.Value = Request.QueryString["bid"];
            hidAlterFor.Value = Request.QueryString["aid"];
            hidFrom.Value = Request.QueryString["from"];
            hidTo.Value = Request.QueryString["to"];

            Shuba.Business.AlternateUM bl = new Shuba.Business.AlternateUM();
            Shuba.Model.AlternateUMInfo _en = bl.Get(hidOldUnitCode.Value, hidOldNIP.Value, hidAlterFor.Value, Convert.ToDateTime(hidFrom.Value), Convert.ToDateTime(hidTo.Value));

            txtBranchCode.Text = _en.BRANCH_ID;
            txtNIP.Text = _en.NIP;
            ddlAltFor.SelectedValue = _en.ALTERNATE_FOR;
            txtStartDate.Text = _en.EFF_DATE_FROM.ToString("dd MMMM yyyy");
            txtToDate.Text = _en.EFF_DATE_TO.ToString("dd MMMM yyyy");
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Shuba.Business.AlternateUM bl = new Shuba.Business.AlternateUM();
            Shuba.Model.AlternateUMInfo en = new Shuba.Model.AlternateUMInfo();

            Shuba.Business.Branch blBranch = new Shuba.Business.Branch();
            Shuba.Business.User blUser = new Shuba.Business.User();
                        
            bool IsValid = true;
            string ActType = "UPDATE";
            string SPAWEBAppCode = ConfigurationManager.AppSettings["app.code"];
            string SPADAAppCode = ConfigurationManager.AppSettings["app.code.spada"];

            if (IsValid)
            {
                if (blBranch.Get(txtBranchCode.Text.Trim()).BranchName == null)
                {
                    IsValid = false;

                    msg = "Invalid Unit Code";
                    Alert(msg);
                }
            }

            if (IsValid && blUser.Get(txtNIP.Text.Trim(), SPAWEBAppCode).Name == null)
            {
                if (blUser.Get(txtNIP.Text.Trim(), SPADAAppCode).Name == null)
                {
                    IsValid = false;

                    msg = "Invalid NIP\\nPlease make sure NIP is correct and already registered in Application Console Management"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                    Alert(msg);
                }
            }

            Shuba.Model.AlternateUMInfo bi = new Shuba.Model.AlternateUMInfo();
            bi = bl.GetUnionTmp(txtBranchCode.Text.Trim(), txtNIP.Text.Trim());

            if (hidOldNIP.Value == "" && bi.ALTERNATE_FOR == "UM")
            {
                IsValid = false;

                msg = "Alternate UM is already registered for this NIP";
                Alert(msg);
            }

            if (IsValid && (ddlAltFor.SelectedValue == "UM"))
            {
                bi = bl.GetExistingAlternateUM(txtBranchCode.Text.Trim(), txtNIP.Text.Trim());

                List<Shuba.Model.AlternateUMInfo> bil = new List<Shuba.Model.AlternateUMInfo>();
                bil = bl.GetAlternateUM(txtBranchCode.Text.Trim());

                if (bi.NIP != null)
                {
                    if (!Validate(bil, Convert.ToDateTime(txtStartDate.Text), Convert.ToDateTime(txtToDate.Text)))
                    {
                        IsValid = false;

                        msg = "Alternate UM is already registered in this Unit\\nPlease validate your entry";
                        Alert(msg);
                    }
                }
                /*
                else
                {   
                    if (!Validate(bil, Convert.ToDateTime(txtStartDate.Text), Convert.ToDateTime(txtToDate.Text)))
                    {
                        IsValid = false;

                        msg = "Alternate UM is already registered for this Unit with the same Effective date";
                        Alert(msg);
                    }
                }     
                */ 
            }

            if (IsValid && ((Convert.ToDateTime(txtToDate.Text).Date < Convert.ToDateTime(txtStartDate.Text).Date) || Convert.ToDateTime(txtToDate.Text).Date < ProcessingDate().Date || Convert.ToDateTime(txtStartDate.Text).Date < ProcessingDate().Date))
            {
                IsValid = false;

                msg = "Invalid Effective Date\\nPlease make sure Date is correct\\n- End Date must be equal or greater than Start Date\\n- Effective Date must be equal or greater than Today"; 
                Alert(msg);
            }

            if (IsValid)
            {
                DateTime dtOut = ProcessingDate();
                if (hidOldNIP.Value == "" && hidOldUnitCode.Value == "")
                {
                    ActType = "INSERT";
                    en.BRANCH_ID_ORIG = txtBranchCode.Text.Trim();
                    en.NIP_ORIG = txtNIP.Text.Trim();
                    en.ALTERNATE_FOR_ORIG = ddlAltFor.SelectedValue;
                    en.EFF_DATE_FROM_ORIG = DateTime.TryParse(txtStartDate.Text, out dtOut) == true ? Convert.ToDateTime(txtStartDate.Text) : ProcessingDate();
                    en.EFF_DATE_TO_ORIG = DateTime.TryParse(txtToDate.Text, out dtOut) == true ? Convert.ToDateTime(txtToDate.Text) : ProcessingDate();
                }
                else
                {
                    ActType = "UPDATE";
                    en.BRANCH_ID_ORIG = hidOldUnitCode.Value;
                    en.NIP_ORIG = hidOldNIP.Value;
                    en.ALTERNATE_FOR_ORIG = hidAlterFor.Value;
                    en.EFF_DATE_FROM_ORIG = Convert.ToDateTime(hidFrom.Value);
                    en.EFF_DATE_TO_ORIG = Convert.ToDateTime(hidTo.Value);
                }
                
                en.BRANCH_ID = txtBranchCode.Text.Trim();
                en.NIP = txtNIP.Text.Trim();
                en.ALTERNATE_FOR = ddlAltFor.SelectedValue;
                en.EFF_DATE_FROM = DateTime.TryParse(txtStartDate.Text, out dtOut) == true ? Convert.ToDateTime(txtStartDate.Text) : ProcessingDate();
                en.EFF_DATE_TO = DateTime.TryParse(txtToDate.Text, out dtOut) == true ? Convert.ToDateTime(txtToDate.Text) : ProcessingDate();
                en.ENTRY_BY = HttpContext.Current.User.Identity.Name;
                en.ENTRY_DATE = ProcessingDate();
                en.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                en.UPDATE_DATE = ProcessingDate();
                en.ACT_TYPE = ActType;
                en.IS_ACTIVE = "1";

                try
                {
                    bl.Save(en);

                    AddLog(ActType, ActType + " ALTERNATE UM");
                    msg = this.GetGlobalResourceObject("Messages", "SaveAlert").ToString();
                    AlertAndRedirect(msg, "alternate_um_list.aspx");
                }
                catch (Exception ex)
                {
                    ErrBox.Visible = true;
                    ErrMsg.Text = ex.Message;
                }
            }
        }

        private bool Validate(List<Shuba.Model.AlternateUMInfo> list, DateTime StartFromEntry, DateTime StartToEntry)
        {
            List<DateTime> Entry = new List<DateTime>();
            for (DateTime i = StartFromEntry.Date; i <= StartToEntry.Date; i = i.AddDays(1))
            {
                Entry.Add(i);
            }

            foreach (Shuba.Model.AlternateUMInfo bi in list)
            {
                List<DateTime> Existing = new List<DateTime>();
                for (DateTime i = bi.EFF_DATE_FROM.Date; i <= bi.EFF_DATE_TO.Date; i = i.AddDays(1))
                {
                    Existing.Add(i);
                }
                
                foreach (DateTime item in Entry)
                {
                    if (Existing.Contains(item))
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("alternate_um_list.aspx");
        }
    }
}
